export class LocalStorageVar<D> {
  data: D
  private initValue: D
  private localStorageId: string
  constructor(initValue: D, localStorageId: string) {
    this.data = initValue
    this.initValue = initValue
    this.localStorageId = localStorageId
  }

  init() {
    const setStr = localStorage.getItem(this.localStorageId)
    if (!setStr) return
    const saveValue = JSON.parse(setStr)
    if (typeof this.data !== typeof saveValue) return
    if (Array.isArray(this.data) && !Array.isArray(saveValue)) return
    this.data = saveValue
  }
  set(setValue: D) {
    this.data = setValue
    localStorage.setItem(this.localStorageId, JSON.stringify(setValue))
  }
  clear() {
    localStorage.removeItem(this.localStorageId)
    this.data = this.initValue
  }
}
